package com.meego.common.database.pool;

import java.sql.Connection;
import java.sql.SQLException;
import com.jolbox.bonecp.BoneCP;

public class TransactionFrame {
	private boolean connected;
	private Connection connection;
	private boolean mAutoCommit;
	private String mConnectionName;

	public TransactionFrame(String aName, boolean autoCommit) {
		this.mConnectionName = aName;
		this.connected = true;
		this.mAutoCommit = autoCommit;
	}

	public TransactionFrame(boolean autoCommit) {
		this.mConnectionName = "default";
		this.connected = true;
		this.mAutoCommit = autoCommit;
	}

	public Connection connection() throws Exception {
		if (!connected)
			throw new IllegalStateException("Transaction Frame is Closed");

		if (connection == null) {
			BoneCP boneCP = BoneCPPool.getInstance().getBoneCP(this.mConnectionName);
			System.out.println("Trying to connect to: " + this.mConnectionName + " pool");
			if (boneCP != null) {
				System.out.println(this.mConnectionName + " pool found");
				this.connection = boneCP.getConnection();

				if (!this.mAutoCommit)
					this.connection.setAutoCommit(false);
			} else {
				System.out.println(this.mConnectionName + " pool not found");
			}
		}

		return this.connection;
	}

	/*Commit a transaction*/
	public boolean commit() throws Exception {
		if (this.mAutoCommit)
			throw new IllegalStateException("Cannot commit an AutoCommit Transaction Frame");
		if (!connected)
			return true;
		System.out.println("commit a Transcation Frame");
		if (this.connection == null)
			return false;

		try {
			this.connection.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}

		this.mAutoCommit = true;
		/*set autocommit because it will be returned to poool with default auto commit = true*/
		this.connection.setAutoCommit(true);
		return true;
	}

	/*rollback a transaction*/
	public boolean rollback() throws Exception {
		if (this.mAutoCommit) throw new IllegalStateException("Cannot rollback an AutoCommit Transaction Frame");
		if (!connected) return true;
		System.out.println("rollback a Transcation Frame");
		if (this.connection == null)
			return false;

		try {
			this.connection.rollback();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}

		this.mAutoCommit = true;
		/*set autocommit because it will be returned to poool with default auto commit = true*/
		this.connection.setAutoCommit(true);
		return true;
	}

	/*return a connection to Pool*/
	public void close() {
		if (!(this.mAutoCommit))
			throw new IllegalStateException("Cannot close Transaction Frame without commit/rollback");

		System.out.println("Closing Transaction Frame");
		this.connected = false;
		if (this.connection == null)
			return;

		try {
			this.connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		this.connection = null;
	}
}
